﻿using Newtonsoft.Json.Linq;

using PLCS.Domain.Configs;
using PLCS.Domain.Equipments;
using PLCS.EntityFrameworkCore.EntityFrameworkCore;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PLCS.EntityFrameworkCore.Configs
{
    public class BackDataRepository : EfCoreRepository<PLCSDbContext, BackData, Guid>, IBackDataRepository
    {
        public BackDataRepository(IDbContextProvider<PLCSDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<string?> GetBackDataByKeyAsync(string key, string header)
        {
            var entity = await FindAsync(x => x.Key == key);
            if (entity == null)
                return null;

            return GetValueFromJson(entity.Value, header);
        }

        private static string? GetValueFromJson(string json, string fieldPath)
        {
            try
            {
                JObject jsonObject = JObject.Parse(json);
                JToken token = jsonObject.SelectToken(fieldPath);

                return token?.ToString();
            }
            catch (Exception ex)
            {
                // JSON 解析出错
                Console.WriteLine("Error parsing JSON: " + ex.Message);
                return null;
            }
        }
    }
}